import { Table, Button, message } from 'antd';
import React, { Component } from 'react';
import "./dyeTable.css";

class DynTable extends Component {
    constructor(props) {
        super(props);
        this.state = {
            url: props.url,
            data: props.data,
            tableTitle: props.tableTitle == null ? "" : props.tableTitle,
            isNeedActionCol: props.isNeedActionCol == null ? false : props.isNeedActionCol,
            tableData: [],
            tableCol: [],
        };
        this.refresh = this.refresh.bind(this);
        this.operatingStg = this.operatingStg.bind(this);
    }

    componentWillMount() {
        this.queryStgInfo(this.state.url, this.state.data);
        console.log("componentWillMount");
    }

    refresh = () => {
        this.queryStgInfo(this.state.url, this.state.data);
    }

    /**
     * 向服务器发送查询策略请求
     * @param {String} url 111
     * @param {String} data 请求数据 ip=172.0.0.1&mac=1234:56&server_id=1&token=9c1d97a415853b97e99ee2200c6ce7d4
     */
    queryStgInfo = (url, data) => {
        console.log("开始发送查询策略请求，登录url=" + url + data);
        fetch(url + data, {
            method: "GET", // *GET, POST, PUT, DELETE, etc.
            mode: "cors", // no-cors, cors, *same-origin
            cache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cached
            credentials: "same-origin", // include, *same-origin, omit
            headers: {
                "Content-Type": "application/json; charset=utf-8",
            },
            redirect: "follow", // manual, *follow, error
            referrer: "no-referrer", // no-referrer, *client
        })
            .then(response => response.json()).then(
                resJson => {
                    if (resJson.ret_code === 0) {
                        console.log("查询策略信息成功！返回消息：" + JSON.stringify(resJson));
                        this.queryOk(resJson);
                    } else {
                        console.log("查询策略信息成功！返回消息：" + JSON.stringify(resJson));
                        this.queryFaild(resJson);
                    }
                }) // JSON-string from `response.json()` call
            .catch(error => {
                console.error(error)
                message.error("查询策略信息失败：" + error);
            }); // parses response to JSON
    }

    /**查询成功 */
    queryOk = (data) => {
        this.createTable(data);
    }

    /**查询失败 */
    queryFaild = (data) => {
        message.error("刷新失败：" + data.ret_msg);
    }

    /**
     * 创建表格
     */
    createTable = (resData) => {
        let curCols = this.getTableCols(resData);
        let curTableData = this.getTableData(resData);

        this.setState({ tableCol: curCols });
        this.setState({ tableData: curTableData });
    }

    /**
     * 创建列
     * @param {*} resData 
     */
    getTableCols = (resData) => {
        let displayCols = [];
        let colList = resData.columns;

        //响应有误
        if (colList == undefined) {
            console.log("响应无columns数据：columns=[" + colList + "]");
            return displayCols;
        }


        colList.forEach((colName, index) => {
            let col = {
                title: colName,
                dataIndex: colName,
                key: colName,
            };
            //多列溢出控制
            this.addMuitlColsControl((colList.length > 8), col)
            displayCols.push(col);
        });

        //action列
        this.addActionCol(this.state.isNeedActionCol, displayCols);

        console.log("创建表格列成功：" + displayCols.toLocaleString());
        return displayCols;
    }

    /**
     * 多列溢出控制——针对表格列太多，固定primary列宽度
     */
    addMuitlColsControl = (isNeed, col) => {
        if (!isNeed) {
            return;
        }
        col['width'] = 150;
    }

    /**
     * 添加操作列
     */
    addActionCol = (isNeed, displayCols) => {
        if (!isNeed) {
            return;
        }
        let opCol = {
            title: 'Action',
            key: 'action',
            render: (text, record) => (
                <Button type="primary" icon="setting" onClick={this.operatingStg} />
            ),
        };
        displayCols.push(opCol);
    }

    operatingStg = (ev) => {
        console.log("开始操作策略！");
        // this.queryOprStg(stg);
    }

    /** 格式化响应数据 */
    getTableData = (resJson) => {
        let rawColumns = resJson.columns;
        let rawData = resJson.data;
        let formatList = [];

        if (rawColumns == undefined || rawData == undefined) {
            console.log("响应无data数据：columns=[" + rawColumns + "]、data=[" + rawData + "]");
            return formatList;
        }

        for (let i = 0; i < rawData.length; i++) {
            const data = rawData[i];
            let formatObj = { key: '' + i };
            for (let j = 0; j < rawColumns.length; j++) {
                const key = rawColumns[j];
                const value = data[j];
                formatObj[key] = value;
            }
            formatList.push(formatObj);
        }

        console.log("格式化响应数据成功：" + formatList.toLocaleString());
        return formatList;
    }

    /**
     *map转换为json
     */
    mapToJson(map) {
        return JSON.stringify(this.strMapToObj(map));
    }

    render() {
        return (
            <div id="stgInfoTable">
                <Button className="refBtn" type='primary' onClick={this.refresh}>刷新</Button>
                <Table bordered title={this.state.tableTitle} columns={this.state.tableCol} dataSource={this.state.tableData} scroll={{ x: 1300 }} />
            </div>
        );
    }
}
export default DynTable;